package com.rolerealm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rolerealm.common.constant.ErrorCode;
import com.rolerealm.common.exception.BusinessException;
import com.rolerealm.dao.CharacterMapper;
import com.rolerealm.dao.CharacterPersonalityMapper;
import com.rolerealm.domain.dto.CharacterCreateDTO;
import com.rolerealm.domain.dto.CharacterSearchDTO;
import com.rolerealm.domain.dto.CharacterUpdateDTO;
import com.rolerealm.domain.entity.CharacterEntity;
import com.rolerealm.domain.entity.CharacterPersonalityEntity;
import com.rolerealm.domain.vo.CharacterDetailVO;
import com.rolerealm.domain.vo.CharacterVO;
import com.rolerealm.domain.vo.PageResult;
import com.rolerealm.domain.vo.PresetInitResult;
import com.rolerealm.service.CharacterService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 角色管理服务实现类
 * 
 * @author RoleRealm Team
 * @version 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CharacterServiceImpl implements CharacterService {

    private final CharacterMapper characterMapper;
    private final CharacterPersonalityMapper characterPersonalityMapper;

    @Override
    public PageResult<CharacterVO> getCharacters(CharacterSearchDTO searchDTO) {
        log.debug("查询角色列表，搜索条件：{}", searchDTO);
        
        // 构建分页参数
        Page<CharacterEntity> page = new Page<>(searchDTO.getPage(), searchDTO.getSize());
        
        // 执行查询
        IPage<CharacterEntity> result = characterMapper.selectCharactersPage(page, searchDTO);
        
        // 转换为VO
        List<CharacterVO> characterVOs = result.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        return PageResult.of(characterVOs, searchDTO.getPage(), searchDTO.getSize(), result.getTotal());
    }

    @Override
    public CharacterDetailVO getCharacterDetail(Long characterId) {
        log.debug("查询角色详情，角色ID：{}", characterId);
        
        // 查询角色基础信息
        CharacterEntity character = characterMapper.selectById(characterId);
        if (character == null) {
            throw new BusinessException(ErrorCode.CHARACTER_NOT_FOUND);
        }
        
        // 查询角色性格特征
        CharacterPersonalityEntity personality = characterPersonalityMapper.selectByCharacterId(characterId);
        
        // 转换为详情VO
        CharacterDetailVO detailVO = convertToDetailVO(character, personality);
        
        log.debug("角色详情查询成功，角色名称：{}", character.getName());
        return detailVO;
    }

    @Override
    public PageResult<CharacterVO> searchCharacters(CharacterSearchDTO searchDTO) {
        log.debug("搜索角色，搜索条件：{}", searchDTO);
        
        // 构建分页参数
        Page<CharacterEntity> page = new Page<>(searchDTO.getPage(), searchDTO.getSize());
        
        // 执行全文搜索
        IPage<CharacterEntity> result = characterMapper.searchCharactersPage(page, searchDTO);
        
        // 转换为VO
        List<CharacterVO> characterVOs = result.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        return PageResult.of(characterVOs, searchDTO.getPage(), searchDTO.getSize(), result.getTotal());
    }

    @Override
    public List<CharacterVO> getCharactersByIds(List<Long> characterIds) {
        log.debug("批量查询角色，角色ID列表：{}", characterIds);
        
        if (characterIds == null || characterIds.isEmpty()) {
            return Collections.emptyList();
        }
        
        List<CharacterEntity> characters = characterMapper.selectByIds(characterIds);
        
        return characters.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public CharacterDetailVO getCharacterById(Long characterId) {
        return getCharacterDetail(characterId);
    }

    @Override
    public PresetInitResult initPresetCharacters() {
        log.info("开始初始化预设角色库");
        
        // 检查是否已有预设角色
        LambdaQueryWrapper<CharacterEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CharacterEntity::getCategory, "历史人物");
        Long existingCount = characterMapper.selectCount(wrapper);
        
        if (existingCount > 0) {
            log.info("预设角色已存在，跳过初始化");
            return PresetInitResult.builder()
                    .initializedCount(0)
                    .characters(Collections.emptyList())
                    .build();
        }
        
        // 创建预设角色数据
        List<CharacterEntity> presetCharacters = createPresetCharacters();
        
        // 批量插入角色
        int insertedCount = 0;
        List<PresetInitResult.PresetCharacterInfo> characterInfos = new ArrayList<>();
        
        for (CharacterEntity character : presetCharacters) {
            try {
                characterMapper.insert(character);
                insertedCount++;
                
                // 创建性格特征
                createCharacterPersonality(character);
                
                characterInfos.add(PresetInitResult.PresetCharacterInfo.builder()
                        .id(character.getId())
                        .name(character.getName())
                        .category(character.getCategory())
                        .build());
                
                log.debug("预设角色创建成功：{}", character.getName());
            } catch (Exception e) {
                log.error("预设角色创建失败：{}", character.getName(), e);
            }
        }
        
        log.info("预设角色初始化完成，成功创建{}个角色", insertedCount);
        
        return PresetInitResult.builder()
                .initializedCount(insertedCount)
                .characters(characterInfos)
                .build();
    }

    @Override
    public List<CharacterVO> getPopularCharacters(Integer limit) {
        log.debug("查询热门角色，限制数量：{}", limit);
        
        List<CharacterEntity> characters = characterMapper.selectPopularCharacters(limit);
        
        return characters.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<CharacterVO> getCharactersBySkillType(String skillType, Integer limit) {
        log.debug("根据技能类型查询角色，技能类型：{}，限制数量：{}", skillType, limit);
        
        List<CharacterEntity> characters = characterMapper.selectBySkillType(skillType, limit);
        
        return characters.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    /**
     * 转换为角色VO
     */
    private CharacterVO convertToVO(CharacterEntity entity) {
        CharacterVO vo = new CharacterVO();
        BeanUtils.copyProperties(entity, vo);
        return vo;
    }

    /**
     * 转换为角色详情VO
     */
    private CharacterDetailVO convertToDetailVO(CharacterEntity character, CharacterPersonalityEntity personality) {
        CharacterDetailVO detailVO = new CharacterDetailVO();
        BeanUtils.copyProperties(character, detailVO);
        
        if (personality != null) {
            detailVO.setSpeakingStyle(personality.getSpeakingStyle());
            detailVO.setEmotionalRange(personality.getEmotionalRange());
            
            // 解析性格特征JSON
            if (StringUtils.hasText(personality.getPersonalityTraits())) {
                try {
                    // 这里可以添加JSON解析逻辑
                    // 暂时使用空Map
                    detailVO.setPersonalityTraits(new HashMap<>());
                } catch (Exception e) {
                    log.warn("解析性格特征JSON失败：{}", personality.getPersonalityTraits(), e);
                    detailVO.setPersonalityTraits(new HashMap<>());
                }
            }
        }
        
        return detailVO;
    }

    /**
     * 创建预设角色数据
     */
    private List<CharacterEntity> createPresetCharacters() {
        List<CharacterEntity> characters = new ArrayList<>();
        
        // 苏格拉底
        characters.add(CharacterEntity.builder()
                .name("苏格拉底")
                .description("古希腊哲学家，西方哲学的奠基者")
                .background("苏格拉底是古希腊哲学家，被认为是西方哲学的奠基者。他以问答法著称，通过不断提问来引导人们思考真理。")
                .personality("智慧、思辨、善于提问、耐心、坚定")
                .era("古代")
                .region("希腊")
                .category("历史人物")
                .skillType("qa")
                .avatarUrl("https://example.com/socrates.jpg")
                .language("zh")
                .status(1)
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .deleted(0)
                .build());
        
        // 莎士比亚
        characters.add(CharacterEntity.builder()
                .name("莎士比亚")
                .description("英国文学巨匠，戏剧大师")
                .background("威廉·莎士比亚是英国文学史上最杰出的戏剧家和诗人，被誉为'人类文学奥林匹斯山上的宙斯'。")
                .personality("才华横溢、富有想象力、情感丰富、善于表达")
                .era("文艺复兴")
                .region("英国")
                .category("历史人物")
                .skillType("creative")
                .avatarUrl("https://example.com/shakespeare.jpg")
                .language("zh")
                .status(1)
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .deleted(0)
                .build());
        
        // 爱因斯坦
        characters.add(CharacterEntity.builder()
                .name("爱因斯坦")
                .description("理论物理学家，相对论创立者")
                .background("阿尔伯特·爱因斯坦是20世纪最伟大的物理学家之一，创立了相对论，对现代物理学产生了深远影响。")
                .personality("聪明、好奇、幽默、谦逊、富有想象力")
                .era("现代")
                .region("德国")
                .category("历史人物")
                .skillType("qa")
                .avatarUrl("https://example.com/einstein.jpg")
                .language("zh")
                .status(1)
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .deleted(0)
                .build());
        
        // 达芬奇
        characters.add(CharacterEntity.builder()
                .name("达芬奇")
                .description("文艺复兴时期的天才艺术家和发明家")
                .background("列奥纳多·达·芬奇是意大利文艺复兴时期的天才，既是画家、雕塑家，也是发明家、科学家。")
                .personality("多才多艺、好奇心强、观察敏锐、富有创造力")
                .era("文艺复兴")
                .region("意大利")
                .category("历史人物")
                .skillType("creative")
                .avatarUrl("https://example.com/davinci.jpg")
                .language("zh")
                .status(1)
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .deleted(0)
                .build());
        
        // 孔子
        characters.add(CharacterEntity.builder()
                .name("孔子")
                .description("中国古代思想家、教育家，儒家学派创始人")
                .background("孔子是中国古代伟大的思想家、教育家，儒家学派的创始人，其思想影响中国两千多年。")
                .personality("智慧、仁爱、谦逊、好学、正直")
                .era("古代")
                .region("中国")
                .category("历史人物")
                .skillType("qa")
                .avatarUrl("https://example.com/confucius.jpg")
                .language("zh")
                .status(1)
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .deleted(0)
                .build());
        
        return characters;
    }

    /**
     * 创建角色性格特征
     */
    private void createCharacterPersonality(CharacterEntity character) {
        CharacterPersonalityEntity personality = CharacterPersonalityEntity.builder()
                .characterId(character.getId())
                .personalityTraits("{\"wisdom\": 95, \"curiosity\": 90, \"patience\": 85}")
                .speakingStyle("善于用问题引导思考")
                .emotionalRange("理性、温和、坚定")
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .build();
        
        characterPersonalityMapper.insert(personality);
    }

    @Override
    public CharacterVO createCharacter(CharacterCreateDTO createDTO) {
        log.debug("创建角色，角色名称：{}", createDTO.getName());
        
        // 检查角色名称是否已存在
        LambdaQueryWrapper<CharacterEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CharacterEntity::getName, createDTO.getName());
        CharacterEntity existingCharacter = characterMapper.selectOne(wrapper);
        if (existingCharacter != null) {
            throw new BusinessException(ErrorCode.CHARACTER_NAME_DUPLICATE);
        }
        
        // 创建角色实体
        CharacterEntity character = CharacterEntity.builder()
                .name(createDTO.getName())
                .description(createDTO.getDescription())
                .background(createDTO.getBackground())
                .personality(createDTO.getPersonality())
                .era(createDTO.getEra())
                .region(createDTO.getRegion())
                .category(createDTO.getCategory())
                .skillType(createDTO.getSkillType())
                .avatarUrl(createDTO.getAvatarUrl())
                .language(createDTO.getLanguage())
                .status(createDTO.getStatus())
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .deleted(0)
                .build();
        
        // 插入角色
        int result = characterMapper.insert(character);
        if (result <= 0) {
            throw new BusinessException(ErrorCode.CHARACTER_CREATE_FAILED);
        }
        
        log.info("角色创建成功，角色ID：{}，角色名称：{}", character.getId(), character.getName());
        
        return convertToVO(character);
    }

    @Override
    public CharacterVO updateCharacter(CharacterUpdateDTO updateDTO) {
        log.debug("更新角色，角色ID：{}", updateDTO.getId());
        
        // 检查角色是否存在
        CharacterEntity existingCharacter = characterMapper.selectById(updateDTO.getId());
        if (existingCharacter == null) {
            throw new BusinessException(ErrorCode.CHARACTER_NOT_FOUND);
        }
        
        // 检查角色名称是否重复（如果更新了名称）
        if (updateDTO.getName() != null && !updateDTO.getName().equals(existingCharacter.getName())) {
            LambdaQueryWrapper<CharacterEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CharacterEntity::getName, updateDTO.getName())
                    .ne(CharacterEntity::getId, updateDTO.getId());
            CharacterEntity duplicateCharacter = characterMapper.selectOne(wrapper);
            if (duplicateCharacter != null) {
                throw new BusinessException(ErrorCode.CHARACTER_NAME_DUPLICATE);
            }
        }
        
        // 更新角色信息
        CharacterEntity character = CharacterEntity.builder()
                .id(updateDTO.getId())
                .name(updateDTO.getName() != null ? updateDTO.getName() : existingCharacter.getName())
                .description(updateDTO.getDescription() != null ? updateDTO.getDescription() : existingCharacter.getDescription())
                .background(updateDTO.getBackground() != null ? updateDTO.getBackground() : existingCharacter.getBackground())
                .personality(updateDTO.getPersonality() != null ? updateDTO.getPersonality() : existingCharacter.getPersonality())
                .era(updateDTO.getEra() != null ? updateDTO.getEra() : existingCharacter.getEra())
                .region(updateDTO.getRegion() != null ? updateDTO.getRegion() : existingCharacter.getRegion())
                .category(updateDTO.getCategory() != null ? updateDTO.getCategory() : existingCharacter.getCategory())
                .skillType(updateDTO.getSkillType() != null ? updateDTO.getSkillType() : existingCharacter.getSkillType())
                .avatarUrl(updateDTO.getAvatarUrl() != null ? updateDTO.getAvatarUrl() : existingCharacter.getAvatarUrl())
                .language(updateDTO.getLanguage() != null ? updateDTO.getLanguage() : existingCharacter.getLanguage())
                .status(updateDTO.getStatus() != null ? updateDTO.getStatus() : existingCharacter.getStatus())
                .createdAt(existingCharacter.getCreatedAt())
                .updatedAt(LocalDateTime.now())
                .deleted(existingCharacter.getDeleted())
                .build();
        
        // 更新角色
        int result = characterMapper.updateById(character);
        if (result <= 0) {
            throw new BusinessException(ErrorCode.CHARACTER_UPDATE_FAILED);
        }
        
        log.info("角色更新成功，角色ID：{}，角色名称：{}", character.getId(), character.getName());
        
        return convertToVO(character);
    }

    @Override
    public Boolean deleteCharacter(Long characterId) {
        log.debug("删除角色，角色ID：{}", characterId);
        
        // 检查角色是否存在
        CharacterEntity character = characterMapper.selectById(characterId);
        if (character == null) {
            throw new BusinessException(ErrorCode.CHARACTER_NOT_FOUND);
        }
        
        // 逻辑删除角色
        int result = characterMapper.deleteById(characterId);
        if (result <= 0) {
            throw new BusinessException(ErrorCode.CHARACTER_DELETE_FAILED);
        }
        
        // 删除关联的性格特征
        characterPersonalityMapper.deleteByCharacterId(characterId);
        
        log.info("角色删除成功，角色ID：{}，角色名称：{}", characterId, character.getName());
        
        return true;
    }

    @Override
    public Integer batchDeleteCharacters(List<Long> characterIds) {
        log.debug("批量删除角色，角色ID列表：{}", characterIds);
        
        if (CollectionUtils.isEmpty(characterIds)) {
            return 0;
        }
        
        int successCount = 0;
        for (Long characterId : characterIds) {
            try {
                deleteCharacter(characterId);
                successCount++;
            } catch (Exception e) {
                log.error("删除角色失败，角色ID：{}", characterId, e);
            }
        }
        
        log.info("批量删除角色完成，成功删除{}个角色", successCount);
        
        return successCount;
    }

    @Override
    public Boolean updateCharacterStatus(Long characterId, Integer status) {
        log.debug("更新角色状态，角色ID：{}，状态：{}", characterId, status);
        
        // 检查角色是否存在
        CharacterEntity character = characterMapper.selectById(characterId);
        if (character == null) {
            throw new BusinessException(ErrorCode.CHARACTER_NOT_FOUND);
        }
        
        // 更新状态
        character.setStatus(status);
        character.setUpdatedAt(LocalDateTime.now());
        
        int result = characterMapper.updateById(character);
        if (result <= 0) {
            throw new BusinessException(ErrorCode.CHARACTER_UPDATE_FAILED);
        }
        
        log.info("角色状态更新成功，角色ID：{}，状态：{}", characterId, status);
        
        return true;
    }
}
